//
//  HWUndoViewController.m
//  HWanGame
//
//  Created by 陈道斌 on 2021/7/22.
//  Copyright © 2021 Chendaobin. All rights reserved.
//

#import "HWUndoViewController.h"
#import "LFOpinionView.h"

#define MAX_LIMIT_NUMS 90
@interface HWUndoViewController ()<UITextViewDelegate>
@property (nonatomic, strong) LFOpinionView *textView;
@property(strong,nonatomic) UIView *lowerPartView;
@property(strong,nonatomic) UIButton *ttijiaoBut;



@end

@implementation HWUndoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self  setupUI];
    [self addLowerPartView];
    
    
}


- (void)setupUI {
    
    self.navigationItem.title = @"撤销";
    self.view.backgroundColor = RGB(247, 247, 247);
    
     UILabel  *chexiaoLabel  = [[UILabel alloc]initWithFrame:CGRectMake(15, CF_NavHeight,kScreenW-60, 37)];
   //  self.huishouxuzhiLabel.backgroundColor = RGB(255, 217, 161);
//    self.huishouxuzhiLabel.layer.cornerRadius = 32;
//    self.huishouxuzhiLabel.layer.masksToBounds = YES;
    chexiaoLabel.textColor = RGB(68 , 68, 68);
    chexiaoLabel.textAlignment = NSTextAlignmentLeft;
    chexiaoLabel.font = [UIFont systemFontOfSize:16];
    chexiaoLabel.text = @"撤销理由";
    [self.view addSubview:chexiaoLabel];
    
    
    
    _textView = [[LFOpinionView alloc] init];
    _textView.alwaysBounceVertical = YES;
    _textView.delegate = self;
//     _textView.x = 10;
//     _textView.y = 0;
    _textView.frame = CGRectMake(15,CF_NavHeight+37, kScreenW- 30, 155);
    _textView.backgroundColor = [UIColor whiteColor];
     _textView.backgroundColor = RGB(245, 245, 245);
    _textView.textColor = RGB(68, 68, 68);
    _textView.placeholder = @"请输入你的撤销理由";
    _textView.font = [UIFont systemFontOfSize:14];
    _textView.layer.cornerRadius =10 ;
    _textView.layer.masksToBounds = YES;
    _textView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_textView];


    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shouqijianpan)];
    
    [self.view addGestureRecognizer:tap1];
   
    
    
}

- (void)shouqijianpan {
    
    [self.view endEditing:YES];
    
    
}


- (void)addLowerPartView {
    
    self.lowerPartView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenH-44-CF_TabbarSafeBottomMargin, kScreenW, 44+CF_TabbarSafeBottomMargin)];
    // self.lowerPartView.backgroundColor = [UIColor yellowColor];
    self.lowerPartView.backgroundColor = RGB(247, 247, 247);
    [self.view addSubview:self.lowerPartView];
    
    UIButton *butt  = [UIButton setButtonWithFrame:CGRectMake(15, 0, kScreenW-15*2, 34) Title:@"提交" Image:nil Font:13 Color:RGB(255, 255, 155) Target:self Selector:@selector(buttonTap:)];
   //   self.downloadBut = butt;
     butt.backgroundColor = RGB(38, 154, 255);
     butt.layer.cornerRadius = 5;
     butt.layer.masksToBounds = YES;
     butt.backgroundColor = [UIColor bm_colorGradientChangeWithSizeView: butt kaish:RGB(146, 180, 255) endjishu:RGB(79, 134, 255)];
    self.ttijiaoBut = butt;
    
     [self.lowerPartView addSubview:butt];
    
}




//点击提交按钮
- (void)buttonTap:(UIButton *)sender  {
    
     
 
    if (!(self.textView.text.length > 0)) {
        
        [MBProgressHUD showError:@"请输入撤销原因"];
        
        return;
        
        
    }
    
    
    NSString *userID = [HWLocallyStoredData getLoginUserID];
    NSString *tStr = [NSString stringWithFormat:@"%ld",[WMUtil getTimeSp]];
    NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,self.idStr,@"fsd213ewdsadqwe2121213edsad"];
    NSString *signMD5 = [WMUtil md5HexDigest:sign];
    NSDictionary *parametes = @{
                                @"ct" :  @"app",
                                @"ac" : @"recover_chexiao",
                                @"ios" : @"1",
                                @"uid" :userID,
                                @"id": self.idStr,
                                @"content":self.textView.text,
                                @"sign": signMD5
                                };
    
    
    [MBProgressHUD show:@"正在提交"];
    
    [HWWebUtils do3GetWithParameters:parametes progress:nil success:^(id response) {
        
      
        NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
     //   [MBProgressHUD hideHUD];
        
        
        if ([codeStr intValue] == 1) {
         
//            [self.ttijiaoBut  setTitle:@"提交成功" forState:UIControlStateNormal];
//            [self.ttijiaoBut setImage:[UIImage imageNamed:@"chengicodhdf"] forState:UIControlStateNormal];
//            [self.ttijiaoBut  layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:5];
//
          
            [self.navigationController  popViewControllerAnimated:YES];

        } else {
            
             // [MBProgressHUD  showError:@"加载失败"];
             
            
        }
        NSLog(@"%@",response);
        
        
    } failure:^(NSString *error) {
      
        [MBProgressHUD  showError:@"加载失败"];
        
    }];
    

    

    
    
    
    
    
}





//第一个方法用于限制输入，第二个方法用于动态计算剩余字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range

 replacementText:(NSString *)text

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    //获取高亮部分内容

    //NSString * selectedtext = [textView textInRange:selectedRange];

    

    //如果有高亮且当前字数开始位置小于最大限制时允许输入

    if (selectedRange && pos) {

        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];

        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];

        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);

        

        if (offsetRange.location < MAX_LIMIT_NUMS) {

            return YES;

        }

        else

        {
            [MBProgressHUD showError:@"最多只能输入120个字符"];

            return NO;

        }

    }

    

    

    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];

    

    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;

    

    if (caninputlen >= 0)

    {

        return YES;

    }

    else

    {

        NSInteger len = text.length + caninputlen;

        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错

        NSRange rg = {0,MAX(len,0)};

        

        if (rg.length > 0)

        {

            NSString *s = @"";

            //判断是否只普通的字符或asc码(对于中文和表情返回NO)

            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];

            if (asc) {

                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错

            }

            else

            {

                __block NSInteger idx = 0;

                __block NSString  *trimString = @"";//截取出的字串

                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个

                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])

                                         options:NSStringEnumerationByComposedCharacterSequences

                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {

                                          

                                          if (idx >= rg.length) {

                                              *stop = YES; //取出所需要就break，提高效率

                                              return ;

                                          }

                                          

                                          trimString = [trimString stringByAppendingString:substring];

                                          

                                          idx++;

                                      }];

                

                s = trimString;

            }

            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)

            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];

            //既然是超出部分截取了，哪一定是最大限制了。

         //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%d个字",0];

        }
        
        
         [MBProgressHUD showError:@"最多只能输入120个字符"];

        return NO;

    }

    

}

@end
